package mta.command.generate;

import au.com.bytecode.opencsv.CSVWriter;
import mta.localization.LocalizationPackage;
import mta.localization.LocalizationPackageFactory;
import mta.selector.PhraseSelector;
import mta.selector.TemplateSelector;
import mta.selector.UntranslatedSelector;
import org.apache.commons.cli.ParseException;

import java.io.FileWriter;
import java.io.IOException;

/**
 * Magento Translation Assistant
 * Copyright (c) 2009 Dmitry Nikolaev
 * Contact author: blackliteon@gmail.com
 */
public class GeneratePatchBuilder {

    private String[] args;

    public GeneratePatchBuilder(String[] args) {
        this.args = args;
    }

    public GeneratePatch buildPatchGenerator() {

        GeneratePatchBuilderOptions builderOptions = new GeneratePatchBuilderOptions(args);
        try {
            builderOptions.parse();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        String localizationPath = builderOptions.getLocalizationPath();
        String destFile = builderOptions.getFilePath();

        LocalizationPackage lPackage = new LocalizationPackageFactory().build(localizationPath);
        PhraseSelector selector = null;

        switch (builderOptions.getSelectorType()) {

            case ByTemplate:
                selector = new TemplateSelector(lPackage, builderOptions.getTemplate());
                break;
            case Untranslated:
                selector = new UntranslatedSelector(lPackage);
                break;
        }

        try {
            return new GeneratePatch(selector, new CSVWriter(new FileWriter(destFile)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}